package dog.weatherwallpaper;

import java.util.Arrays;

import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.Toast;
import dog.weatherwallpaper.utils.App;
import dog.weatherwallpaper.utils.Conversion;
import dog.weatherwallpaper.utils.Strings;

/**
 * All pixel values are in dp (density-independent pixels): position, textSize and lineSpacing.
 * Calculations are also in dp, px used only to draw.
 */
@SuppressWarnings("deprecation")
public final class SettingsActivity extends PreferenceActivity implements
		SharedPreferences.OnSharedPreferenceChangeListener {

	private SharedPreferences sp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.settings);
		sp = PreferenceManager.getDefaultSharedPreferences(this);

		Preference setWP = (Preference) findPreference(getString(R.string.set_wallpaper_key));
		setWP.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
			@Override
			public boolean onPreferenceClick(Preference arg0) {
				App.toast(R.string.choose_wallpaper, Toast.LENGTH_SHORT);
				startActivityForResult(new Intent(Intent.ACTION_SET_WALLPAPER), 1);
				return true;
			}
		});

		Preference image = (Preference) findPreference(getString(R.string.bg_image_key));
		image.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
			@Override
			public boolean onPreferenceClick(Preference arg0) {
				Intent i = new Intent(Intent.ACTION_PICK);
				i.setType("image/*");
				startActivityForResult(i, 1);
				return true;
			}
		});
		image.setEnabled(sp.getBoolean(getString(R.string.image_key), false));

		CheckBoxPreference celsius = (CheckBoxPreference) findPreference(getString(R.string.temperature_key));
		celsius.setSummaryOn("10" + App.context().getString(R.string.c));
		celsius.setSummaryOff("50" + App.context().getString(R.string.f));
		CheckBoxPreference km = (CheckBoxPreference) findPreference(getString(R.string.distance_key));
		km.setSummaryOn("8 " + App.context().getString(R.string.km));
		km.setSummaryOff("5 " + App.context().getString(R.string.mi));

		EditTextPreference position = (EditTextPreference) findPreference(getString(R.string.position_key));
		CharSequence title = App.context().getString(R.string.position_title) + " [" + this.getMinPosition() + "-"
				+ this.getMaxPosition() + "]";
		position.setTitle(title);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String filePath = cursor.getString(columnIndex);
			cursor.close();

			sp.edit().putString(getString(R.string.bg_image_key), filePath).commit();
			updateSummary(R.string.bg_image_key);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		sp.unregisterOnSharedPreferenceChangeListener(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		sp.registerOnSharedPreferenceChangeListener(this);
		this.updateSummary(R.string.update_interval_key, R.string.position_key, R.string.days_key,
				R.string.text_size_key, R.string.line_spacing_key, R.string.typeface_key, R.string.text_color_key,
				R.string.bg_color_key, R.string.bg_image_key, R.string.temperature_key, R.string.distance_key);
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
		if (key.equals(getString(R.string.position_key))) {
			EditTextPreference edit = (EditTextPreference) findPreference(key);
			int value = Strings.tryParse(edit.getText());
			if (value == -1) {
				App.toast(R.string.field_required, Toast.LENGTH_SHORT);
				revert(edit);
				return;
			} else if (value > this.getMaxPosition()) {
				String text = getString(R.string.max_value) + ' ' + this.getMaxPosition();
				App.toast(text, Toast.LENGTH_SHORT);
				revert(edit);
				return;
			} else if (value < this.getMinPosition()) {
				String text = getString(R.string.min_value) + ' ' + this.getMinPosition();
				App.toast(text, Toast.LENGTH_SHORT);
				revert(edit);
				return;
			}
		} else if (Arrays.asList(getString(R.string.text_size_key), getString(R.string.update_interval_key)).contains(
				key)) {
			EditTextPreference edit = (EditTextPreference) findPreference(key);
			int value = Strings.tryParse(edit.getText());
			if (value == -1) {
				App.toast(R.string.field_required, Toast.LENGTH_SHORT);
				revert(edit);
				return;
			} else if (value == 0) {
				String text = getString(R.string.min_value) + " 1";
				App.toast(text, Toast.LENGTH_SHORT);
				revert(edit);
				return;
			} else if (key.equals(getString(R.string.update_interval_key)) && value > 24) {
				String text = getString(R.string.max_value) + " 24";
				App.toast(text, Toast.LENGTH_SHORT);
				revert(edit);
				return;
			}
		} else if (key.equals(getString(R.string.image_key))) {
			findPreference(getString(R.string.bg_image_key)).setEnabled(
					sp.getBoolean(getString(R.string.image_key), false));
			return;
		}
		updateSummary(key);

		LocalBroadcastManager.getInstance(App.context()).sendBroadcast(new Intent(WPService.DRAW));
	}

	private void revert(EditTextPreference edit) {
		edit.setText((String) edit.getSummary());
	}

	private void updateSummary(String key) {
		Preference p = findPreference(key);
		if (p instanceof ListPreference) {
			ListPreference list = (ListPreference) p;
			list.setSummary(list.getEntry());
		} else if (p instanceof EditTextPreference) {
			EditTextPreference edit = (EditTextPreference) p;
			edit.setSummary(edit.getText());
		} else if (key.equals(getString(R.string.bg_image_key))) {
			String filePath = App.getStringPreference(R.string.bg_image_key);
			p.setSummary(filePath);
		}
	}

	private void updateSummary(int... keys) {
		for (int eachKey : keys) {
			updateSummary(getString(eachKey));
		}
	}

	private int getMinPosition() {
		int textSize = 0;
		int statusBarSize = 0;
		int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
		if (resourceId > 0) {
			statusBarSize = getResources().getDimensionPixelSize(resourceId);
			textSize = App.getIntPreference(R.string.text_size_key, R.string.text_size_default);
		}
		return Conversion.pxToDp(statusBarSize) + textSize;
	}

	private int getMaxPosition() {
		int screenHeight = getBaseContext().getResources().getDisplayMetrics().heightPixels;
		boolean extraCurrentInfo = sp.getBoolean(getString(R.string.extra_info_key), true);
		int days = App.getIntPreference(R.string.days_key, R.string.days_default);
		int textSize = App.getIntPreference(R.string.text_size_key, R.string.text_size_default);
		int spacing = App.getIntPreference(R.string.line_spacing_key, R.string.line_spacing_default);

		int fullTextSize = (days + (extraCurrentInfo ? 1 : 0)) * (textSize + spacing);
		return Conversion.pxToDp(screenHeight) - fullTextSize;
	}
}